package com.ruoyi.law.factory;

import com.ruoyi.law.enums.ReturnStrategyEnum;
import com.ruoyi.law.factory.inter.DataHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 策略类型工厂
 *
 * @author lie
 * @date 2023/11/15
 */
@Component
public class StrategyTypeFactory implements ApplicationContextAware {

    private final Map<Object, DataHandler> handlerMap = new HashMap<>();

    public DataHandler getDataHandler(Object returnStrategyEnum) {
        return handlerMap.get(returnStrategyEnum);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        addDataHandlerStrategy(applicationContext);
    }

    private void addDataHandlerStrategy(ApplicationContext applicationContext) {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(com.ruoyi.law.annotation.ReturnStrategy.class);
        beansWithAnnotation.forEach((k, v) -> {
            com.ruoyi.law.annotation.ReturnStrategy returnStrategy = v.getClass().getAnnotation(com.ruoyi.law.annotation.ReturnStrategy.class);
            ReturnStrategyEnum returnStrategyEnum = returnStrategy.returnStrategy();
            handlerMap.put(returnStrategyEnum, (DataHandler) v);
        });
    }

}
